<template>
    <div class="app-container">
        <div class="customContainer" v-show="tab_view==1">
            <!-- 搜索头 -->
            <el-form :inline="true" :model="formInline" size="small">
                <el-form-item>
                    <el-select
                            placeholder="选择门店"
                            v-model="formInline.store_id"
                            @change="listArray"
                            style="width:250px"
                            filterable>
                        <el-option
                                v-for="item in store_list"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-date-picker style="width:240px" v-model="pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels range-separator="-"
                                    :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"  @change="timeListArray()"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <span style="color: #888;">类型：</span>
                    <el-select
                            v-model="formInline.type"
                            style="width: 150px"
                            placeholder="请选择">
                        <el-option
                                v-for="item in type_list"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <span style="color: #888;">状态：</span>
                    <el-select
                            v-model="formInline.status"
                            style="width: 150px"
                            placeholder="请选择">
                        <el-option
                                v-for="item in state_list"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input type="text" v-model="formInline.name" placeholder="请输入方案名称" style="width: 200px;margin:0 10px"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="listArray">搜索</el-button>
                </el-form-item>
                <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">新增发放包</el-button>
            </el-form>

            <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading">
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
                </el-table-column>

                <el-table-column align="center" label="名称" prop="name"></el-table-column>
                <el-table-column align="center" label="类型" prop="name" width="120px">
                    <template slot-scope="scope">
                        <span>{{scope.row.type=='1'?'生日福利':'卡升级福利'}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="创建时间" prop="create_time"></el-table-column>
                <el-table-column align="center" label="状态" width="100px">
                    <template slot-scope="scope">{{scope.row.status==1?"已启用":"已停用"}}</template>
                </el-table-column>
                <el-table-column align="center" label='操作' width="330">
                    <template slot-scope="scope">
                        <el-button  type="primary" plain size="mini" @click="signEnables(scope.row)">{{scope.row.status==1?'停用':'启用'}}</el-button>
                        <el-button  type="primary" plain size="mini" @click="details(scope.row)">详情</el-button>
                        <el-button  type="primary" plain size="mini" @click="details(scope.row,1)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 短信详情-->
        <div v-show="tab_view==2" class="customContainer">
            <el-button class="pull-left" type="primary" size="small" @click="backClick">返 回</el-button>
            <div class="tab_title">{{top_title}}</div>
            <div class="info">
                <el-form
                        :model="infoFormObject"
                        ref="infoForm"
                        :rules="rules"
                        :disabled="isDisabled"
                        label-width="80px"
                >
                    <div class="op_title" >基础信息</div>
                    <el-form-item label="名称" label-width="100px">

                    </el-form-item>
                    <el-form-item label="类型" label-width="100px">
                        <el-select
                                v-model="formInline.type"
                                style="width: 150px"
                                placeholder="请选择">
                            <el-option
                                    v-for="item in type_list"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>


            </div>
        </div>


        <!-- 弹框 -->
        <el-dialog  title="限购数量" :visible.sync="storeDialog" width="500px">
            <div class="stroe_dialog">
                <span>名称：{{storeDialogObj.name}}</span>
            </div>
            <el-form>
                <el-form-item label="限购">
                    <el-input type="text"></el-input>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 自定义底部 -->
        <div class="bottom_box" v-show="tab_view==1">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                           layout="prev, pager, next, jumper" :total="totalDataNumber">
            </el-pagination>
        </div>
    </div>
</template>
<script>
    import {
        getStore,
        getCardList,
        signSave,
        getInfoPage,
        getInfo,
        signEnable,
        signDetails,
        rulesStore,
        rulesUpdate
    } from "@/api/operation/integral_scheme";

    import {
        pickerOptionsF,
        pickerDateOneMonth,
    } from "@/utils";

    import {
        CNname,
        num1to999999
    } from "@/utils/validate";
    let cardList=[];
    export default {
        name: 'grant_management',
        data(){
            return{
                list: null,  //数据
                store_list:[],
                pickerOptions: pickerOptionsF(),
                pickerDate: pickerDateOneMonth(),
                top_title:"新增发放包",
                tab_view:1,
                listLoading: false,  //表格换场动画
                isDisabled:false, //是否可更改
                alter:false,
                currentPage: 1,
                totalDataNumber: 0,
                state_list:[{id:"-1",name:"全部"},{id:"0",name:"已停用"},{id:"1",name:"已启用"}],
                type_list:[{id:"-1",name:"全部"},{id:"0",name:"生日福利"},{id:"1",name:"办卡升级福利"}],
                addTypeDialog: false, // 弹窗是否显示
                formInline: {  //开始时间，结束时间
                    begin_time: "",
                    end_time: "",
                    store_id:"",
                    status:"-1",
                    name:"",
                    type:""
                },
            }
        },
        mounted() {
            this.getstore();
            this.getCardType();
        },
        methods:{
            getstore() {
                getStore({ category_id: 717 }).then((response) => {
                    this.store_list = response;
                    let data = response.filter(
                        res => res.id == this.$store.getters.optionId
                    );
                    if (data.length > 0) {
                        this.formInline.store_id = data[0].id;
                    }
                    this.timeListArray();
                }).then(()=>{
                    this.listArray();
                })
            },
            timeListArray(){  //时间选择
                this.formInline.begin_time=this.pickerDate[0];
                this.formInline.end_time=this.pickerDate[1];
            },
            listArray(){  //获取数据
                this.listLoading = true;
                this.list = [];
                getInfoPage(this.formInline).then(response=>{
                    this.totalDataNumber = response.data.count / 1;
                    if (this.totalDataNumber == 0) {
                        this.listLoading = false;
                    } else {
                        getInfo(this.formInline).then(res=>{
                            this.list = res.data;
                            this.listLoading = false;
                        });
                    }
                });
            },
            handleCurrentChange(val) {  //获取某个分页的数据
                this.listLoading = true;
                getInfo(this.formInline,val).then(res=>{
                    this.list = res.data;
                    this.listLoading = false;
                }).catch(res => {
                    this.listLoading = false;
                });
            },
            saveUpdate(){  //修改
                if(!CNname(this.infoForm.name)){
                    this.$message.error("请填写正确的方案名称（1-15个汉字）");
                    return
                }
                if(!this.infoForm.color){
                    this.$message.error("请选择方案标记色");
                    return
                }
                rulesUpdate({
                    id:this.infoForm.ruleId,
                    store_id:this.formInline.store_id,
                    name:this.infoForm.name,
                    color:this.infoForm.color,
                }).then((res)=>{
                    if(res.code==1){
                        this.listArray();
                        this.clearDate();
                        this.addTypeDialog = false;
                        this.$message.success(res.message);
                    }
                })
            },
            saveClick(){
                let json_list=[];
                if(!CNname(this.infoForm.name)){
                    this.$message.error("请填写正确的方案名称（1-15个汉字）");
                    return
                }
                if(!this.infoForm.color){
                    this.$message.error("请选择方案标记色");
                    return
                }

                if(this.infoForm.json_list.length == 0){
                    this.$message.error("请添加积分规则");
                    return
                }
                console.log(this.infoForm);
                let json=[];
                for(let i=0;i<this.infoForm.json_list.length;i++){
                    json.push({
                        card_type_id:this.infoForm.json_list[i].card_type_id,
                        limit:this.infoForm.json_list[i].limit,
                        score:this.infoForm.json_list[i].score,
                    })
                }
                let data={
                    store_id:this.formInline.store_id,
                    name:this.infoForm.name,
                    color:this.infoForm.color,
                    json_list:json,
                }
                console.log(data)

                signSave(data).then(res=>{
                    if(res.code==1){
                        this.listArray();
                        this.clearDate();
                        this.addTypeDialog = false;
                        this.$message.success(res.message);
                    }
                })
            },
            signEnables(row){
                if(row.status==1){
                    this.$confirm('是否确定停用该方案？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(()=>{
                        signEnable({id:row.id,status:"0",store_id:this.formInline.store_id}).then(res=>{
                            if(res.code==1){
                                this.$message.success(res.message);
                                this.listArray();
                            }
                        });
                    }).catch(() => {
                        row.status = true;
                    });
                }else{
                    signEnable({id:row.id,status:"1",store_id:this.formInline.store_id}).then(res=>{
                        if(res.code==1){
                            this.$message.success(res.message);
                            this.listArray();
                        }
                    });
                }
            },
            details(row,index){
                signDetails({id:row.id}).then(res=>{
                    if(res.code==1 && res.data.length!=0){
                        this.addTypeDialog = true;
                        this.isDisabled=true;
                        if(index){
                            this.alter = false;
                        }else{
                            this.alter = true;
                        }
                        console.log(this.colorlist.filter(item=>item.name == res.data[0].color));
                        this.infoForm.name = row.name;
                        this.infoForm.ruleId = row.id;

                        this.infoForm.color = this.colorlist.filter(item=>item.name == res.data[0].color)[0].name;
                        this.dialoigTableList.forEach(value => {
                            value.rule =`消费${value.limit}${value.type==0?'币':value.type=='1'?'次':'星'}得${value.score}积分`
                        })

                        this.infoForm.json_list = res.data; //全部数据
                        this.dialoigDataNumber = this.infoForm.json_list.length / 1;  //数据数量

                        let arraylist;
                        let num = this.dialoigCurrentPage * this.dialoigPageSize;

                        if(this.dialoigDataNumber<=this.dialoigPageSize){
                            arraylist = this.infoForm.json_list.slice(0,this.dialoigPageSize);
                        }else{
                            arraylist = this.infoForm.json_list.slice(num-this.dialoigPageSize,num);
                        }
                        this.dialoigTableList = arraylist;

                    }else{
                        this.addTypeDialog = true;
                        this.isDisabled=true;
                        this.dialoigTableList = [];
                    }
                });
            },
            addTypeClick() {
                this.isDisabled = false;
                this.addTypeDialog = true;
            },
            clearDate(){
                this.cardUnit="";
                this.limit="";
                this.score="";
                this.card_type_id="";
                this.dialoigTableList=[{}];
                this.infoForm={
                    ruleId: "",
                    name:"",
                    color:"",
                    json_list:[]
                }
                this.dialoigDataNumber = 0;
                this.card_old_list = JSON.parse(JSON.stringify(cardList));
                this.card_type_list = this.cardTypeGroup(this.card_old_list);
            },
            closeDialoig(){
                if(!this.isDisabled || !this.alter){
                    this.$confirm("方案尚未保存，关闭后数据清空，是否关闭", "提示", {
                        type: "warning"
                    }).then(() => {
                        this.clearDate();
                        this.addTypeDialog = false;
                    }).catch(()=>{
                        this.addTypeDialog = true;
                    });
                }else{
                    this.clearDate();
                    this.addTypeDialog = false;
                }
            }
        }
    };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .customContainer {
        overflow-y: auto;
    }
    .main{
        display: flex;
        flex-wrap: wrap;
        div{
            width: 40px;
            height: 40px;
            margin-right:10px;
            position: relative;

            span{
                color: white;
                font-size: 28px;
                font-weight: bold;
                position: absolute;
                bottom: 5px;
                right: 5px;
            }
        }
    }
    .op_title {
        margin: 30px 0 20px;
        font-size: 18px;
        font-weight: bold;
        color: #282828;
        padding:0 0 10px 0px;
        box-sizing: border-box;
        border-bottom: 1px solid #dcdfe6;
    }

    .main_botton{
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        button{
            width: 100px;
            height: 35px;
            line-height: 10px;
        }
    }
    .stroe_dialog{
        margin-bottom: 15px;
        display: flex;
        align-items: center;

        span:nth-child(2){
            display: block;
            width: 80px;
            height: 35px;
            margin-left: 20px;
        }
    }
</style>
